Telegram Group & Telegram Channel
В Python оператор квадратных скобок [] можно переопределить, реализовав магический метод __getitem__. Это позволяет, например, создать объект, который виртуально содержит бесконечное количество повторяющихся элементов:


class Cycle:
def __init__(self, lst):
self._lst = lst

def __getitem__(self, index):
return self._lst[index % len(self._lst)]

print(Cycle(['a', 'b', 'c'])[100]) # 'b'


Необычность оператора [] в Python в том, что он поддерживает особый синтаксис. Его можно использовать не только так: [2], но и так: [2:10], [2:10:2], [2::2] или даже [:]. Смысл такой записи — [start:stop:step], но в ваших собственных объектах вы можете использовать этот синтаксис как угодно.

Что же передаётся в __getitem__ в таких случаях? Объекты slice созданы специально для этого.

Пример:


class Inspector:
def __getitem__(self, index):
print(index)

Inspector()[1]
# 1

Inspector()[1:2]
# slice(1, 2, None)

Inspector()[1:2:3]
# slice(1, 2, 3)

Inspector()[:]
# slice(None, None, None)

Inspector()[:, 0, :]
# (slice(None, None, None), 0, slice(None, None, None))


Объект slice сам по себе ничего не делает — он просто хранит атрибуты start, stop и step:


s = slice(1, 2, 3)
print(s.start) # 1
print(s.stop) # 2
print(s.step) # 3


👉@BookPython



tg-me.com/BookPython/3650
Create:
Last Update:

В Python оператор квадратных скобок [] можно переопределить, реализовав магический метод __getitem__. Это позволяет, например, создать объект, который виртуально содержит бесконечное количество повторяющихся элементов:


class Cycle:
def __init__(self, lst):
self._lst = lst

def __getitem__(self, index):
return self._lst[index % len(self._lst)]

print(Cycle(['a', 'b', 'c'])[100]) # 'b'


Необычность оператора [] в Python в том, что он поддерживает особый синтаксис. Его можно использовать не только так: [2], но и так: [2:10], [2:10:2], [2::2] или даже [:]. Смысл такой записи — [start:stop:step], но в ваших собственных объектах вы можете использовать этот синтаксис как угодно.

Что же передаётся в __getitem__ в таких случаях? Объекты slice созданы специально для этого.

Пример:


class Inspector:
def __getitem__(self, index):
print(index)

Inspector()[1]
# 1

Inspector()[1:2]
# slice(1, 2, None)

Inspector()[1:2:3]
# slice(1, 2, 3)

Inspector()[:]
# slice(None, None, None)

Inspector()[:, 0, :]
# (slice(None, None, None), 0, slice(None, None, None))


Объект slice сам по себе ничего не делает — он просто хранит атрибуты start, stop и step:


s = slice(1, 2, 3)
print(s.start) # 1
print(s.stop) # 2
print(s.step) # 3


👉@BookPython

BY Библиотека Python разработчика | Книги по питону


Warning: Undefined variable $i in /var/www/tg-me/post.php on line 283

Share with your friend now:
tg-me.com/BookPython/3650

View MORE
Open in Telegram


Библиотека Python разработчика Telegram | DID YOU KNOW?

Date: |

Telegram Be The Next Best SPAC

I have no inside knowledge of a potential stock listing of the popular anti-Whatsapp messaging app, Telegram. But I know this much, judging by most people I talk to, especially crypto investors, if Telegram ever went public, people would gobble it up. I know I would. I’m waiting for it. So is Sergei Sergienko, who claims he owns $800,000 of Telegram’s pre-initial coin offering (ICO) tokens. “If Telegram does a SPAC IPO, there would be demand for this issue. It would probably outstrip the interest we saw during the ICO. Why? Because as of right now Telegram looks like a liberal application that can accept anyone - right after WhatsApp and others have turn on the censorship,” he says.

Telegram has exploded as a hub for cybercriminals looking to buy, sell and share stolen data and hacking tools, new research shows, as the messaging app emerges as an alternative to the dark web.An investigation by cyber intelligence group Cyberint, together with the Financial Times, found a ballooning network of hackers sharing data leaks on the popular messaging platform, sometimes in channels with tens of thousands of subscribers, lured by its ease of use and light-touch moderation.Библиотека Python разработчика from sg


Telegram Библиотека Python разработчика | Книги по питону
FROM USA